package com.pine.manager.pineframework.trigger.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.pine.common.redis.cache.RedisCache;
import com.pine.common.trigger.AbstractTriggerTemplate;
import com.pine.common.trigger.TriggerContext;
import com.pine.common.util.async.AsyncComponent;
import com.pine.common.util.async.AsyncUtil;
import com.pine.dao.pineframework.constants.StatusEnum;
import com.pine.manager.config.ThreadPoolConfig;
import com.pine.manager.core.CacheNameConstant;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.SysConfigManager;
import com.pine.manager.pineframework.bo.SysConfigBo;
import com.pine.manager.pineframework.query.SysConfigQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * <p>
 * 系统配置表 刷新缓存 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-13
 */
@Component
@Slf4j
public class SysConfigRefreshCacheTrigger extends AbstractTriggerTemplate<String, Boolean> {

    @Resource
    private RedisCache redisCache;

    @Resource(name = ThreadPoolConfig.BIZ_EXECUTOR_NAME)
    private Executor executor;

    @Resource
    private SysConfigManager sysConfigManager;

    public SysConfigRefreshCacheTrigger() {
        super(TriggerTypeEnum.SYS_CONFIG_REFRESH_CACHE);
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    public Boolean trigger(TriggerContext<String> triggerContext) {
        // 获取缓存名称
        String cacheName = triggerContext.getTriggerRequest();
        if (StrUtil.isBlank(cacheName)) {
            cacheName = CacheNameConstant.SYS_CONFIG_CACHE_NAME;
        }

        // 查询现有的配置信息
        SysConfigQuery query = new SysConfigQuery();
        query.setStatus(StatusEnum.ENABLE);
        List<SysConfigBo> sysConfigBos = sysConfigManager.list(query);

        // 如果存在配置，则先清空缓存，再给缓存中设置值
        if (CollUtil.isNotEmpty(sysConfigBos)) {
            log.info("清空缓存{}", cacheName);
            // 清空缓存
            redisCache.removeAll(cacheName);

            AsyncComponent asyncComponent = AsyncUtil.getAsyncComponent(executor);
            final String finalCacheName = cacheName;
            // 异步设置缓存
            for (SysConfigBo sysConfigBo : sysConfigBos) {
                asyncComponent.addRunTask(() -> redisCache.set(finalCacheName, sysConfigBo.getConfigKey(), sysConfigBo));
            }
            asyncComponent.execute();
            log.info("刷新缓存{}", cacheName);
            return true;
        }
        return false;
    }
}
